class Solution {
    vector<int> tmp;
public:
    int reversePairs(vector<int>& nums) {
        tmp.resize(nums.size());
        return mergeSortCnt(nums, 0, nums.size() - 1);
    }
 
    int mergeSortCnt(vector<int>& nums, int left, int right)
    {   // 解法一：升序
        if(left >= right)
            return 0;
        int ret = 0, mid = (left + right) >> 1;
        // 先计算左右两侧翻转对数量
        ret += mergeSortCnt(nums, left, mid);
        ret += mergeSortCnt(nums, mid + 1, right);
 
        // 计算翻转对数量
        int cur1 = left, cur2 = mid + 1, i = left;
        while(cur2 <= right) // 升序的情况
        {
            while(cur1 <= mid && nums[cur2] >= nums[cur1] / 2.0)
            {
                cur1++;
            }
            if(cur1 > mid)
                break;
            ret += mid - cur1 + 1;
            cur2++;
        }
 
        // 合并两个有序数组
        cur1 = left, cur2 = mid + 1;
        while(cur1 <= mid && cur2 <= right)
            tmp[i++] = nums[cur1] <= nums[cur2] ? nums[cur1++] : nums[cur2++];
        
		while (cur1 <= mid) 
            tmp[i++] = nums[cur1++];
		while (cur2 <= right) 
            tmp[i++] = nums[cur2++];
		for (int j = left; j <= right; j++)
			nums[j] = tmp[j];
        
        return ret;
    }
};